﻿using System.Collections.Generic;
using System.Linq;
using RimWorld;
using RimWorld.Planet;
using UnityEngine;
using Verse;
using Verse.Sound;

namespace ARMIR {
    public class CompShield_listShield : CompShield {
        public new CompProperties_listShield Props => (CompProperties_listShield)props;
        private bool firstFullCharge = true;
        private float energyChargeDely = 0;
        private float reChargeCheckInternal = 60;
        private int nextHitEffectTick;
        private int gapGiveHediff = 0;

        public override void CompDrawWornExtras() {
            Draw();
        }

        public override void PostDraw() {
            Draw();
        }

        public override bool CompAllowVerbCast(Verb verb) {
            return true; // 允许所有武器（包括远程）
        }

        public override void CompTick() {
            base.CompTick();
            energyRecharge();
            if (firstFullCharge) {
                energy = Props.maxEnergy;
                firstFullCharge = false;
            }
            reChargeCheckInternal++;
            if (reChargeCheckInternal >= 60) {
                reChargeCheckInternal = 0;
            }
            if (gapGiveHediff > 0) { 
                gapGiveHediff--;
            }
        }
        public override void PostPreApplyDamage(ref DamageInfo dinfo, out bool absorbed) {
            absorbed = false;
            List<DamageDef> damageDefBlacklist = new List<DamageDef>();
            if (ShieldState != ShieldState.Active || PawnOwner == null)
                return;

            if (energy <= 0) {
                if (gapGiveHediff <= 0) {
                    breakDown();
                }
                energy = 0;
                return;
            }

            int powerBase = (int)ARMIR_ModSettings.powerSet;
            if (Props.damageRelief * powerBase >= 1) {
                energy -= dinfo.Amount / 100 * 0.05f;
            }
            else {
                energy -= dinfo.Amount / 100 * (1f - (Props.damageRelief * powerBase));
            }
            energyChargeDely = Props.reChargeDelay;
            if (Find.TickManager.TicksGame > nextHitEffectTick)
            {
                nextHitEffectTick = Find.TickManager.TicksGame + 80;
            }
            SoundDef.Named("ARMIR_mindShieldHit").PlayOneShot(new TargetInfo(PawnOwner.Position, PawnOwner.Map)); //受击音效
            absorbed = true;
        }
        private void energyRecharge() { 
            if (energyChargeDely <= 0) {
                requireEquipment(out bool hasEquipments);
                if (energy + Props.chargeAmountPerTick <= Props.maxEnergy && hasEquipments) {
                    energy = energy + Props.chargeAmountPerTick;
                }
            }
            else {
                energyChargeDely--;
            }
        }
        private void requireEquipment(out bool hasEquipments) {
            hasEquipments = false;
            if (PawnOwner == null) {
                return;
            }
            bool hasEquipmentA = false;
            if (PawnOwner.equipment.AllEquipmentListForReading.Any(e => e.def == Props.requiredEquipmentA)
                || PawnOwner.apparel.WornApparel.Any(a => a.def == Props.requiredEquipmentA)) { 
                hasEquipmentA = true;
            }
            bool hasEquipmentB = false;
            if (PawnOwner.equipment.AllEquipmentListForReading.Any(e => e.def == Props.requiredEquipmentB)
                || PawnOwner.apparel.WornApparel.Any(a => a.def == Props.requiredEquipmentB))
            {
                hasEquipmentB = true;
            }
            bool hasEquipmentC = false;
            if (PawnOwner.equipment.AllEquipmentListForReading.Any(e => e.def == Props.requiredEquipmentC)
                || PawnOwner.apparel.WornApparel.Any(a => a.def == Props.requiredEquipmentC))
            {
                hasEquipmentC = true;
            }
            if (hasEquipmentA && hasEquipmentB && hasEquipmentC) {
                hasEquipments = true;
            }
        }
        private void Draw()
        {
            float pct = energy / Props.maxEnergy;
            if (PawnOwner != null && !PawnOwner.Faction.IsPlayer && pct < 1 && Find.TickManager.TicksGame < nextHitEffectTick + 1200)
            {
                Material BaseMat = SolidColorMaterials.SimpleSolidColorMaterial(new Color(1f, 1f, 1f, 0.6f));
                Material ChargeMat = SolidColorMaterials.SimpleSolidColorMaterial(new Color(0.4f, 0.8f, 0.8f, 0.8f));
                GenDraw.DrawFillableBar(new GenDraw.FillableBarRequest
                {
                    center = PawnOwner.DrawPos + Vector3.up * 1.5f + Vector3.back * 0.8f,
                    size = new Vector2(0.8f, 0.2f),
                    fillPercent = pct,
                    filledMat = ChargeMat,
                    unfilledMat = BaseMat,
                    margin = 0f
                });
            }
        }
        private void breakDown() {
            //给迷迭香上buff
            var Rosmontis = PawnOwner.Map.mapPawns.AllHumanlikeSpawned.Where(p => p.health.hediffSet.HasHediff(DefDatabase<HediffDef>.GetNamed("ARMIR_OriginiumBrainStem")) && !p.Downed).ToList();
            if (Rosmontis.Count > 0)
            {
                Hediff asYourWish = HediffMaker.MakeHediff(DefDatabase<HediffDef>.GetNamed("ARMIR_AsYourWishHediff"), Rosmontis[0]);
                Rosmontis[0].health.AddHediff(asYourWish);
            }
            gapGiveHediff = 60000;
        }
    }
}